/*
  运行时间: 40ms
  消耗内存 13.3MB
*/
import Foundation

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
  let maxLength = nums.count - 1
  for i in 0...maxLength {
    let k = i + 1
    for j in k..<nums.count {
      if (nums[i] + nums[j] == target) {
        return [i, j]
      }
    }
  }
  return [0]
}

// 执行用时为 32 ms 的范例 [最优的写法]
func twoSum2(_ nums: [Int], _ target: Int) -> [Int] {
  var dict = [Int: Int]()
  for (i, num) in nums.enumerated() {
    print("i=\(i) num=\(num)")
    if let lastIndex = dict[target - num] {
        return [lastIndex, i]
    }
    dict[num] = i
  }
  fatalError("No valid outputs")
}

// test
let nums = [2, 7, 1, 0, 11, 15];
let target = 7;

// let nums = [3, 2, 4]
// let target = 6;
// print(twoSum(nums, target))
print(twoSum2(nums, target))